<?php

namespace app\http\middleware;

use app\facade\Token;
use think\Db;
use app\models\{User as Users};
use app\facade\Redis;

class Auth
{
    use \traits\controller\Jump;
    public function handle($request, \Closure $next)
    {
        $url = '/' . $request->controller() . '/' . $request->action();
        $url = strtolower($url);
        $verify = config('auth.api');
        if (!in_array($url, $verify) && !$request->header('token')) {
            $this->result(null, 999, 'token不能为空');
        }

        if ($request->header('token') && !in_array($url, $verify)) {
            $user_id = Token::get($request->header('token'));
            $user =  (new Users())->where('id', $user_id)->find();
            if (!$user) {
                $this->result(null, 998, '用户账号不存在');
            }
            if ($user['status'] == 1) {
                $this->result(null, 998, '账号已冻结,请联系管理员');
            }
            // if ($request->header('token') != $user['token']) {
            //     $this->result(null, 998, '您的账号已在别处登录，请确保账号安全');
            // }
            $request->user = $user;
            $request->user_id = $user_id;
        }
        //如果是POST提交  全部做验证处理
        if ($request->isPost()) {
            if (empty($user_id)) {
                $code = $request->ip();
            } else {
                $code = $user_id;
            }
            $unique = date('YmdHi') . '_' . $url . '_' . $code;
            $frtimes = Redis::get($unique);
            if ($frtimes) {
                $timerds = Redis::ttl($unique);
                if (empty($timerds)) {
                    $timerds = 1;
                }
                $this->result([], 404, '请求频繁,请' . $timerds . '秒后再试');
            } else {
                Redis::setex($unique, 2, 2);
            }
        }
        return $next($request);
    }
}
